package com.shiguiwu.springboot3.search.controller;

import cn.hutool.core.util.ClassLoaderUtil;
import com.shiguiwu.springboot3.search.dto.index.IndexDTO;
import com.shiguiwu.springboot3.search.enetity.ContentsIndex;
import com.shiguiwu.springboot3.util.R;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 索引controller
 * @author: stone
 * @date: Created by 2023/12/17 15:34
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.search.controller
 */
@RestController
@RequestMapping("/indexs")
@Slf4j
public class IndexController {

    @Autowired
    private ElasticsearchTemplate template;

    @PostMapping("/")
    public R<String> save(@RequestBody IndexDTO indexDTO) throws ClassNotFoundException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (!ClassUtils.isPresent(indexDTO.getClazz(), classLoader)) {
            return R.ok("不存在改索引信息");
        }
        // 处理索引结构
        Class<?> aClass = ClassUtils.forName(indexDTO.getClazz(), Thread.currentThread().getContextClassLoader());
        IndexOperations indexOps = template.indexOps(aClass);

        if (indexOps.exists()){
            boolean delFlag = indexOps.delete();
            log.info("contents_index exists，delete:{}",delFlag);
            indexOps.createMapping(aClass);
        } else {
            log.info("contents_index not exists");
            indexOps.createMapping(aClass);
        }
        // ID查询

        return R.ok("添加成功");
    }

}
